import { _decorator, Component, Node, resources, SpriteFrame, AudioClip, EventTouch, Vec3, Color, Prefab, Label, instantiate, Vec2, Sprite, UITransform, find, AudioSource } from 'cc';
const { ccclass, property } = _decorator;
import { Blueprint } from './Blueprint';

@ccclass('EquipmentBpBox')
export class EquipmentBpBox extends Component {
    @property({type: Node})
    contentNode: Node = null!

    @property({type: Prefab})
    equipmentBpBoxItemPrefab: Prefab = null!

    @property({type: AudioClip})
    selectAudio: AudioClip = null!

    audioSource: AudioSource = null!
    equipmentBpBoxInfo: object = {}
    selectedEquipmentBpBoxItem: Node = null

    start() {
        this.initComponents()
        this.initTouchEvents()
    }

    onEnable() {
        this.getEquipmentBpBoxInfoFromLocalStorage()
    }
    
    /** 
     * @zh
     * 从缓存中获取制作图信息。
    */
    getEquipmentBpBoxInfoFromLocalStorage() {
        if (!localStorage.getItem('lp-equipment-bp-box')) {
            return
        }

        // 移除所有制作图节点
        this.contentNode.removeAllChildren()
        
        // 设置图片和数量
        this.equipmentBpBoxInfo = JSON.parse(localStorage.getItem('lp-equipment-bp-box'))
        for (let key in this.equipmentBpBoxInfo) {
            this.spawnEquipmentBpBoxItem(key)
        }

        // 显示上次选中的制作图
        if (this.selectedEquipmentBpBoxItem){
            let itemKey = this.selectedEquipmentBpBoxItem.name
            for (let i=0; i<this.contentNode.children.length; i++) {
                let equipmentBpBoxItem = this.contentNode.children[i]
                if (equipmentBpBoxItem.name == itemKey) {
                    equipmentBpBoxItem.getComponent(Sprite).color = new Color().fromHEX('ffffff')
                    break
                }
            }
        }
    }

    /** 
     * @zh
     * 更新制作图数量缓存。
    */
    updateEquipmentBpBoxInfo(addOrDel: string, itemKey: string, num:number, equipmentInfo: object=null) {
        if (addOrDel == 'ADD') {
            if (!(itemKey in this.equipmentBpBoxInfo)) {
                this.equipmentBpBoxInfo[itemKey] = equipmentInfo
                
                // 这里的判断，有点神奇。。。，先放着吧
                if (this.equipmentBpBoxInfo[itemKey]) {
                    this.equipmentBpBoxInfo[itemKey]['num'] = 0
                }
                else {
                    return
                }
            }
            
            this.equipmentBpBoxInfo[itemKey]['num'] += num
        }
        else {
            this.equipmentBpBoxInfo[itemKey]['num'] -= num
            
            // 更新显示数字
            this.selectedEquipmentBpBoxItem.children[1].getComponent(Label).string = this.equipmentBpBoxInfo[itemKey]['num'].toString()

            if (this.equipmentBpBoxInfo[itemKey]['num'] <= 0) {
                // 移除相应的制作图信息和节点
                delete this.equipmentBpBoxInfo[itemKey]
                this.selectedEquipmentBpBoxItem.removeFromParent()
            }

            // 肯定是点了使用按钮后数量才会减1，此时玩家再打开面板不应该显示上次选择的制作图
            this.selectedEquipmentBpBoxItem = null
        }

        // 更新缓存
        localStorage.setItem('lp-equipment-bp-box', JSON.stringify(this.equipmentBpBoxInfo))
    }

    /** 
     * @zh
     * 初始化组件。
    */
    initComponents() {
        this.audioSource = find('Canvas').getComponent(AudioSource)
    }

    /** 
     * @zh
     * 初始化触摸事件。
    */
    initTouchEvents() {
        this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this)
    }

    /** 
     * @zh
     * 触摸结束时执行的逻辑。
    */
    onTouchEnd(event: EventTouch) {
        let loc = event.getUILocation()
        let pos = this.contentNode.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(loc.x, loc.y, 0))
        
        for (let i=0; i<this.contentNode.children.length; i++) {
            let equipmentBpBoxItem = this.contentNode.children[i]
            if (equipmentBpBoxItem.getComponent(UITransform).getBoundingBox().contains(new Vec2(pos.x, pos.y))) {
                find('Canvas/Blueprint Background/Blueprint').getComponent(Blueprint).addToUndoStack()
                find('Canvas/Blueprint Background/Blueprint').getComponent(Blueprint).clearRedoStack()

                // 将所有item颜色恢复原状
                this.resetAllItemColor()

                // 将选中的颜色改变
                equipmentBpBoxItem.getComponent(Sprite).color = new Color().fromHEX('ffffff')
                this.selectedEquipmentBpBoxItem = equipmentBpBoxItem

                // 在画板上显示制作图draw()
                let itemKey = equipmentBpBoxItem.name
                console.log(itemKey)
                find('Canvas/Blueprint Background/Blueprint').getComponent(Blueprint).draw(this.equipmentBpBoxInfo[itemKey])

                // 如果是自定义武器则将使用按钮文本设置为AI鉴定按钮
                if (itemKey == 'customWeapon') {
                    find('Canvas/Blueprint Background/Button Layout/Equip Button/Label').getComponent(Label).string = 'AI鉴定'
                }
                else {
                    find('Canvas/Blueprint Background/Button Layout/Equip Button/Label').getComponent(Label).string = '使用'
                }

                // 播放音频
                this.audioSource.playOneShot(this.selectAudio)

                // 更新到缓存中
                break
            }
        }
    }

    /** 
     * @zh
     * 恢复所有制作图节点颜色。
    */
    resetAllItemColor() {
        for (let i=0; i<this.contentNode.children.length; i++) {
            let equipmentBpBoxItem = this.contentNode.children[i]
            equipmentBpBoxItem.getComponent(Sprite).color = new Color().fromHEX('a5a5a5')
        }
    }

    /** 
     * @zh
     * 生成制作图节点。
    */
    spawnEquipmentBpBoxItem(name: string) {
        let num = this.equipmentBpBoxInfo[name]['num']
        let equipmentBpBoxItem = instantiate(this.equipmentBpBoxItemPrefab)
        equipmentBpBoxItem.name = name
        equipmentBpBoxItem.children[1].getComponent(Label).string = num.toString()

        resources.load(this.equipmentBpBoxInfo[name]['picPath'], SpriteFrame, (err: any, spriteFrame: SpriteFrame) => {
            equipmentBpBoxItem.children[0].getComponent(Sprite).spriteFrame = spriteFrame
        })

        this.contentNode.addChild(equipmentBpBoxItem)
    }

    /** 
     * @zh
     * 通过工具名称选择工具，用于撤销重做功能。
    */
    selectnEquipmentBpBoxItemByName(name: string) {
        if (!name) {
            this.resetAllItemColor()
            this.selectedEquipmentBpBoxItem = null
            find('Canvas/Blueprint Background/Blueprint').getComponent(Blueprint).draw(null)
            return
        }
        for (let i=0; i<this.contentNode.children.length; i++) {
            let equipmentBpBoxItem = this.contentNode.children[i]
            if (equipmentBpBoxItem.name == name) {
                // 将所有item颜色恢复原状
                this.resetAllItemColor()

                // 将选中的颜色改变
                equipmentBpBoxItem.getComponent(Sprite).color = new Color().fromHEX('ffffff')
                this.selectedEquipmentBpBoxItem = equipmentBpBoxItem

                // 在画板上显示制作图draw()
                let itemKey = equipmentBpBoxItem.name
                find('Canvas/Blueprint Background/Blueprint').getComponent(Blueprint).draw(this.equipmentBpBoxInfo[itemKey])

                // 如果是自定义武器则将使用按钮文本设置为AI鉴定按钮
                if (itemKey == 'customWeapon') {
                    find('Canvas/Blueprint Background/Button Layout/Equip Button/Label').getComponent(Label).string = 'AI鉴定'
                }
                else {
                    find('Canvas/Blueprint Background/Button Layout/Equip Button/Label').getComponent(Label).string = '使用'
                }

                break
            }
        }
    }
}


